package com.opencv.controller;

import com.opencv.domain.dto.UploadInfoDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author qz.wu
 * @date 2021/9/16 14:23
 * @descriptions 图片文件上传API
 */
@Api(tags = "图片文件上传API")
@RestController("/image/upload")
public class UploadController {

    private static final String UPLOAD_PATH = "E:\\workCode\\opencv-demo\\src\\main\\resources\\upload";

    private static final String UPLOAD_MORE_PATH = "E:\\workCode\\opencv-demo\\src\\main\\resources\\more";

    private static final String UPLOAD_BASE_PATH = "E:\\workCode\\opencv-demo\\src\\main\\resources";

    @ApiOperation("上传头像图片文件")
    @PostMapping("/avatar")
    public String uploadAvatar(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {

        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        File destFile = new File(UPLOAD_PATH + "\\" + fileName);
        // 创建目标文件的存储路径
        destFile.getParentFile().mkdirs();
        // 上传的图片文件转化为目标文件
        file.transferTo(destFile);
        return "success upload : " + fileName;
    }

    @ApiOperation("上传多张头像图片文件")
    @PostMapping("/avatar/more")
    public String uploadMoreAvatar(@RequestParam(value = "files", required = true) MultipartFile[] files) throws IOException {

        if (files.length < 0) {
            return "upload fail.";
        }

        for (int i = 0; i < files.length; i++) {
            String fileName = System.currentTimeMillis() + files[i].getOriginalFilename();
            File destFile = new File(UPLOAD_MORE_PATH + "\\" + fileName);
            // 创建目标文件的存储路径
            destFile.getParentFile().mkdirs();
            // 上传的图片文件转化为目标文件
            files[i].transferTo(destFile);
        }

        return "success upload : " + files.length;
    }

    @ApiOperation("上传多张头像图片文件及上传的文件路径")
    @PostMapping("/avatar/all")
    public String uploadAvatarAndFilePath(@RequestPart(value = "uploadInfoDTO") UploadInfoDTO uploadInfoDTO,
                                          @RequestPart(value = "files", required = true) MultipartFile[] files) throws IOException {

        if (files.length < 0) {
            return "upload fail.";
        }

        for (int i = 0; i < files.length; i++) {
            String fileName = uploadInfoDTO.getUserName() + "\\" + uploadInfoDTO.getImageType()
                    + System.currentTimeMillis() + files[i].getOriginalFilename();
            File destFile = new File(UPLOAD_BASE_PATH + "\\" + fileName);
            // 创建目标文件的存储路径
            destFile.getParentFile().mkdirs();
            // 上传的图片文件转化为目标文件
            files[i].transferTo(destFile);
        }

        return "success upload : " + files.length;
    }
}
